package com.sikaryofficial.backend.controller;

import com.sikaryofficial.backend.config.GuideTaskConfig;
import com.sikaryofficial.backend.constant.RedisCacheKey;
import com.sikaryofficial.backend.domain.vo.UpgradeVO;
import com.sikaryofficial.common.core.domain.R;
import com.sikaryofficial.common.redis.service.RedisService;
import com.sikaryofficial.common.security.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.util.List;

/**
 * 系统更新通知
 */
@RestController
@RequestMapping("/sysNotice")
@Api(tags = "系统特性更新通知")
public class UpdatedMsgController {
    @Autowired
    private RedisService redisService;
    @Resource
    private GuideTaskConfig statisticsMetricsConfig;

    @GetMapping(value = "/content/{businessType}")
    @ApiOperation("通知内容信息")
    public R<UpgradeVO> content(@PathVariable(name = "businessType")
                                                @ApiParam("业务类型: 1: 系统更新通知")
                                                Integer businessType) {
        if (businessType.equals(1)) {
            List<UpgradeVO> result = statisticsMetricsConfig.getSystemUpdateNotices();
            String cacheKey = getReadStatusKey(SecurityUtils.getUserId(), businessType);
            UpgradeVO upgradeVO = result.iterator().next();
            if(Boolean.TRUE.equals(redisService.hasKey(cacheKey))){
                result.iterator().next().setReadStatus(redisService.getCacheObject(cacheKey));
            }else{
                upgradeVO.setReadStatus(false);
            }
            return R.ok(upgradeVO);
        }
        return R.ok(null);
    }

    @GetMapping(value = "/update/{businessType}")
    @ApiOperation("更新业务通知状态")
    public R<String> updateReadStatus(@PathVariable(name = "businessType")
                                      @ApiParam("业务类型: 1: 系统更新通知")
                                      Integer businessType) {
        String cacheKey = getReadStatusKey(SecurityUtils.getUserId(), businessType);
        redisService.setCacheObject(cacheKey, true);
        return R.ok("success");
    }

    private String getReadStatusKey(Long userId, Integer businessType) {
        return MessageFormat.format(RedisCacheKey.BACKEND_UPDATE_READ_KEY, userId.toString(), businessType.toString());
    }

}
